package cn.senwill.controller;

import cn.senwill.domain.Result;
import cn.senwill.service.OrderService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/api/order") // 类级别的映射
public class OrderController {

    private OrderService orderService;

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 创建订单
     * {
     *     "user_id": 1,
     *     "product_id": 1,
     *     "count": 20,
     *     "money": 2000.00
     * }
     * 127.0.0.1:8888/order-service/api/order/add
     * 127.0.0.1:8888/api-gateway/order-service/api/order/add
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "add")
    @SentinelResource(value = "SentinelResource__AddOrder", blockHandler = "addBlockHandler", fallback = "addFallBack")
    @ResponseBody
    public Result add(@RequestBody JSONObject jsonObject) {
        return orderService.add(jsonObject);
    }

    public Result addBlockHandler(BlockException e) {
        return Result.error("限流：A服务调用B服务，B就要对A限流，以确保B服务不会因为过多的请求而过载");
    }

    public Result addFallBack() {
        return Result.error("熔断降级：A服务调用B服务，失败次数达到一定阈值后，A服务的断路器打开,就不在请求B服务，而是直接执行本地的fallback方法 ~");
    }
}